package de.tu_darmstadt.gdi1.battleship.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Vector;

import de.tu_darmstadt.gdi1.battleship.exceptions.InvalidCoordinatesException;

// um Schiffe versenken nicht im character zusammensuchen :D

/**
 * Describes a ship in a Battleship Game
 * 
 */
public class Ship {
	private Coordinates start;
	private int length;
	private boolean vertical, sunk;
	private Vector<Coordinates> coords;

	public Ship() {
		super();
	}

	/**
	 * ship-constructor
	 * 
	 * @param sta
	 *            start coordinates of the ship (lowest x and y)
	 * 
	 * @param len
	 *            length of the ship (2-5)
	 * 
	 * @param v
	 *            true if ship is vertical
	 * @throws InvalidCoordinatesException
	 */
	public Ship(Coordinates sta, int len, boolean v)
			throws InvalidCoordinatesException {
		start = sta;
		length = len;
		vertical = v;
		sunk = false;

		coords = new Vector<Coordinates>(len);
		for (int i = 0; i < len; i++) {
			if (v)
				coords.add(new Coordinates(sta.getX(), sta.getY() + i));
			else
				coords.add(new Coordinates(sta.getX() + i, sta.getY()));
		}

	}

	public boolean isSunk() {
		return sunk;
	}

	public void setSunk(boolean s) {
		sunk = s;
	}

	public int getLength() {
		return length;
	}

	public Coordinates getStart() {
		return start;
	}

	public boolean getVertical() {
		return vertical;
	}

	public Vector<Coordinates> getCoords() {
		return coords;
	}

	/**
	 * saves the informations of a ship into a string
	 * 
	 * @return string with the saved data
	 */
	public String generateSaveString() {
		StringBuffer sb = new StringBuffer("#Ship\n");
		sb.append(start.generateSaveString());
		sb.append(length).append('\n');
		sb.append(vertical).append('\n');
		sb.append(sunk).append('\n');

		sb.append(coords.size()).append('\n');
		for (Coordinates c : coords) {
			sb.append(c.generateSaveString());
		}

		return sb.toString();

	}

	/**
	 * reads a ship save string
	 * 
	 * @param br
	 *            BufferedReader
	 * @throws IOException
	 */
	public void loadSaveString(BufferedReader br) throws IOException {
		if (br.readLine().equals("#Ship")) {
			start = new Coordinates();

			start.loadSaveString(br);
			length = Integer.valueOf(br.readLine());
			vertical = Boolean.valueOf(br.readLine());
			sunk = Boolean.valueOf(br.readLine());

			int x = Integer.valueOf(br.readLine());

			coords = new Vector<Coordinates>(length);
			for (int i = 0; i < x; i++) {
				Coordinates c = new Coordinates();
				c.loadSaveString(br);
				coords.add(c);
			}
		}
	}

}
